package com.wyfx.blockchain.controller;

import com.alibaba.fastjson.JSON;
import com.wyfx.blockchain.common.Constants;
import com.wyfx.blockchain.common.response.MyResponseEntity;
import com.wyfx.blockchain.common.response.ResultResponse;
import com.wyfx.blockchain.config.PackEvent;
import com.wyfx.blockchain.dao.RocksDao;
import com.wyfx.blockchain.service.IBlockService;
import com.wyfx.blockchain.utils.CommonUtils;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.EventListener;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * @Description 导入 添加农业数据
 * @Auther: wsm
 * @Date: 2020/9/7 21:15
 */
@RestController
@RequestMapping("/data")
@Log4j2
@Deprecated
public class DataController {



    /** 
     * 测试合并my-dev 到master分支
     *   111111 2222222
     */

    @Autowired
    private IBlockService iBlockService;

    /**
     * @param data
     * @desc 导入农业数据
     * @Return com.wyfx.blockchain.common.response.ResultResponse
     * @Author wsm
     * @date 2020/9/7 21:22
     */
    @PostMapping("/")
    @ApiOperation("导入数据")
    public ResultResponse addData(@RequestBody String data) {
        iBlockService.addData(data);
        return new ResultResponse(HttpServletResponse.SC_OK);
    }


    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private RocksDao rocksDao;


    //管理端ip和端口
    @Value("${manager.ip}")
    private String managerIp;
    @Value("${manager.port}")
    private Integer managerPort;
    @Value("${group.id}")
    private String groupId;


    /**
     * @desc 查询每次同步到区块链时保存的农业数据 并进行打包成区块上链
     * @Return com.wyfx.blockchain.common.response.ResultResponse
     * @Author wsm
     * @date 2020/9/7 21:43
     */
    @GetMapping("/package")
//    @Scheduled(fixedRate = 600000) //  todo  定时打包数据到主节点 生成区块
    @ApiOperation(value = "测试打包数据到主节点生成区块使用")
    @EventListener(PackEvent.class)// todo 监听发布到容器中的打包数据事件
    public ResultResponse packageData() {

        Map<String, List<String>> map = iBlockService.packageData();

        if (map == null) {
            return new ResultResponse(HttpServletResponse.SC_OK, "没有数据可以打包成区块");
        }
        List<String> dataList = map.get("dataList");
        List<String> keyList = map.get("keyList");

        //  从管理端获取主节点信息
        String managerUrl = CommonUtils.generateUrl(managerIp, managerPort, Constants.GET_MASTER_NODE_INFO);
        MyResponseEntity myResponseEntity = restTemplate.getForObject(managerUrl, MyResponseEntity.class, groupId);
        log.info("resp :{}", myResponseEntity);
        String data = myResponseEntity.getData().toString();
        String urlManager = JSON.parseObject(data, Map.class).get("accessAddress").toString();
        log.info("urlManager:{}", urlManager);

//        String ip = "127.0.0.1";
//        Integer port = 8081;
        String method = "/block/generateBlock";

        //restTemplate 发送json请求
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        //如果数据是list字符串  则接收方需要通过jsonArray解析
        HttpEntity<String> formEntity = new HttpEntity<String>(dataList.toString(), headers);

        //上传打包数据到主节点并生成区块
//        String url = CommonUtils.generateUrl(ip, port, method);
        ResultResponse response = restTemplate.postForObject(urlManager + method, formEntity, ResultResponse.class);

        log.info("打包数据到主节点响应数据:{} ", response);
        //上链成功则删除本地零散数据 重新保存打包好的数据 并在管理端添加一条日志记录
        if (response.getCode() != HttpServletResponse.SC_OK) {
            log.error("生成区块异常:{}", response.getMessage());
            return new ResultResponse(HttpServletResponse.SC_OK, "生成区块异常");
        } else {
            //  清除本地已经生成区块的数据
            for (String s : keyList) {
                rocksDao.delete(s);
            }
            // 清除本地缓存的keysAndIndex
            rocksDao.delete(Constants.KEYS_AND_INDEXS);

        }
        return new ResultResponse(HttpServletResponse.SC_OK, dataList);
    }


    @GetMapping("/heartBeat")
    public ResponseEntity heartBeat() {
        log.info("heart test ");
        return ResponseEntity.ok(HttpServletResponse.SC_OK);
    }

}
